class User < ActiveRecord::Base
  acts_as_authentic

  paginates_per 15

  after_initialize :default_attributes
  
  belongs_to :user_info, :touch => true

  has_and_belongs_to_many :roles, :join_table => "user_has_roles"
  
  has_many :authentications, :dependent => :destroy
  has_many :orders, :through => :user_info

  validates :password, :confirmation => true, :presence => true, :if => lambda {new_record? || !password.nil?}
  validates :email, :presence => true, :format => {:with => Format::EMAIL_REGEX}

  accepts_nested_attributes_for :user_info
  accepts_nested_attributes_for :roles

  def self.has_no_role
    include(:roles).where("user_roles.role IS NULL")
  end

  def self.has_role
    joins(:roles)
  end

  def deliver_user_registration_confirmation!
    email_template = EmailTemplate.find_by_name('user_registration')

    email_template.deliver_to(self.email, {:user => self})
  end

  def role_symbols
    (roles || []).map {|r| r.role.to_sym}
  end

  def has_discount?
    !self.discount.blank?
  end

  def default_attributes
    self.discount = "" if self.discount == 0.0
  end
end